#include "productbrowsepanel.h"
#include <QHeaderView>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <qgroupbox.h>
#include "productdelegate.h"
#include "qdebug.h"

// 构造函数：初始化商品浏览面板，绑定模型与代理
ProductBrowsePanel::ProductBrowsePanel(ProductModel *model, QWidget *parent)
    : QWidget(parent), m_model(model)
{
    // 初始化表格视图，绑定数据模型
    m_tableView = new QTableView(this);
    m_tableView->setModel(m_model);
    m_tableView->setItemDelegate(new ProductDelegate(this));

    // 检查模型是否有效
    if (!m_model) {
        qCritical() << "ProductModel is null!";
        return;
    }

    // 初始化UI布局、信号连接
    setupUI();
    setupConnections();

    // 加载初始数据并更新统计
    refreshData();
}

void ProductBrowsePanel::setupUI()
{
    // 主布局：垂直布局，设置间距与边距
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setSpacing(5); // 减少间距
    m_mainLayout->setContentsMargins(5, 5, 5, 5); // 减少边距

    // 顶部面板：搜索与分类筛选区域
    m_topPanel = new QWidget(this);
    m_topPanel->setFixedHeight(40); // 固定高度
    QHBoxLayout *topLayout = new QHBoxLayout(m_topPanel);
    topLayout->setContentsMargins(0, 0, 0, 0);
    topLayout->setSpacing(5);

    // 搜索框相关控件
    QLabel *searchLabel = new QLabel("搜索:", m_topPanel);
    m_searchEdit = new QLineEdit(m_topPanel);
    m_searchEdit->setPlaceholderText("输入商品名称关键词...");
    m_searchEdit->setClearButtonEnabled(true);

    // 分类筛选下拉框
    QLabel *categoryLabel = new QLabel("分类:", m_topPanel);
    m_categoryFilter = new QComboBox(m_topPanel);
    m_categoryFilter->addItem("全部分类", -1);

    // 从数据库动态加载分类
    QVector<QMap<QString, QVariant>> categories = m_model->getAllCategories();
    for (const auto &category : categories) {
        int categoryId = category["category_id"].toInt();
        QString categoryName = category["category_name"].toString();
        m_categoryFilter->addItem(categoryName, categoryId);
    }

    // 刷新按钮
    m_refreshButton = new QPushButton("刷新", m_topPanel);
    m_refreshButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #f0f0f0;"  // 浅灰色背景
        "   color: black;"               // 黑色文字
        "   border: 1px solid #ccc;"     // 灰色边框
        "   border-radius: 4px;"         // 圆角
        "   padding: 5px 10px;"          // 内边距
        "   min-width: 60px;"            // 最小宽度
        "}"
        "QPushButton:hover {"
        "   background-color: #e0e0e0;"  // 鼠标悬停时背景色变深
        "}"
        "QPushButton:pressed {"
        "   background-color: #d0d0d0;"  // 按下时背景色更深
        "}"
    );

    // 顶部布局控件排列
    topLayout->addWidget(searchLabel);
    topLayout->addWidget(m_searchEdit);

    // 添加90像素的空白间距，让分类筛选框向右移动
    QSpacerItem *spacer = new QSpacerItem(90, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);
    topLayout->addItem(spacer);

    topLayout->addWidget(categoryLabel);
    topLayout->addWidget(m_categoryFilter);
    topLayout->addStretch();

    // 将刷新按钮添加到布局中
    topLayout->addWidget(m_refreshButton);

    // 表格视图配置
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableView->setEditTriggers(QAbstractItemView::DoubleClicked |
                                QAbstractItemView::EditKeyPressed |
                                QAbstractItemView::AnyKeyPressed);
    m_tableView->horizontalHeader()->setStretchLastSection(true);
    m_tableView->verticalHeader()->setVisible(false);
    m_tableView->setSortingEnabled(true);
    m_tableView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 底部面板：使用柔和的绿色渐变背景
    m_bottomPanel = new QWidget(this);
    m_bottomPanel->setFixedHeight(380);
    m_bottomPanel->setObjectName("bottomPanel"); // 设置对象名用于样式表

    // 底部主布局：水平分割为左右两部分
    QHBoxLayout *bottomLayout = new QHBoxLayout(m_bottomPanel);
    bottomLayout->setContentsMargins(15, 15, 15, 15);
    bottomLayout->setSpacing(20);

    // 左侧：添加商品表单
    QWidget *leftPanel = new QWidget(m_bottomPanel);
    leftPanel->setStyleSheet("background: white; border-radius: 6px; padding: 0px;");
    QVBoxLayout *leftMainLayout = new QVBoxLayout(leftPanel);
    leftMainLayout->setContentsMargins(0, 0, 0, 0);

    // 表单标题
    QLabel *formTitle = new QLabel("添加新商品");
    formTitle->setStyleSheet("background: #e9ecef; padding: 10px; border-top-left-radius: 6px; border-top-right-radius: 6px; font-weight: bold;");
    formTitle->setAlignment(Qt::AlignCenter);
    leftMainLayout->addWidget(formTitle);

    // 表单内容
    QWidget *formContent = new QWidget();
    QGridLayout *leftLayout = new QGridLayout(formContent);
    leftLayout->setContentsMargins(15, 15, 15, 15);
    leftLayout->setSpacing(10);
    leftLayout->setColumnMinimumWidth(1, 180); // 确保输入框足够宽

    int row = 0;
    // 商品名称
    leftLayout->addWidget(new QLabel("商品名称:"), row, 0);
    m_productNameEdit = new QLineEdit();
    m_productNameEdit->setPlaceholderText("输入商品名称");
    leftLayout->addWidget(m_productNameEdit, row++, 1);

    // 规格
    leftLayout->addWidget(new QLabel("规格:"), row, 0);
    m_specificationEdit = new QLineEdit();
    m_specificationEdit->setPlaceholderText("输入规格信息");
    leftLayout->addWidget(m_specificationEdit, row++, 1);

    // 颜色
    leftLayout->addWidget(new QLabel("颜色:"), row, 0);
    m_colorEdit = new QLineEdit();
    m_colorEdit->setPlaceholderText("输入颜色");
    leftLayout->addWidget(m_colorEdit, row++, 1);

    // 供应商
    leftLayout->addWidget(new QLabel("供应商:"), row, 0);
    m_supplierEdit = new QLineEdit();
    m_supplierEdit->setPlaceholderText("输入供应商");
    leftLayout->addWidget(m_supplierEdit, row++, 1);

    // 价格行 - 使用水平布局将两个价格字段放在一行
    QHBoxLayout *priceRowLayout = new QHBoxLayout();
    priceRowLayout->setSpacing(15);

    QVBoxLayout *purchasePriceLayout = new QVBoxLayout();
    purchasePriceLayout->addWidget(new QLabel("进货价"));
    m_purchasePriceSpin = new QDoubleSpinBox();
    m_purchasePriceSpin->setRange(0.01, 99999.99);
    m_purchasePriceSpin->setDecimals(2);
    m_purchasePriceSpin->setPrefix("¥ ");
    m_purchasePriceSpin->setValue(0.01);
    purchasePriceLayout->addWidget(m_purchasePriceSpin);

    QVBoxLayout *sellingPriceLayout = new QVBoxLayout();
    sellingPriceLayout->addWidget(new QLabel("售价"));
    m_sellingPriceSpin = new QDoubleSpinBox();
    m_sellingPriceSpin->setRange(0.01, 99999.99);
    m_sellingPriceSpin->setDecimals(2);
    m_sellingPriceSpin->setPrefix("¥ ");
    m_sellingPriceSpin->setValue(0.01);
    sellingPriceLayout->addWidget(m_sellingPriceSpin);

    priceRowLayout->addLayout(purchasePriceLayout);
    priceRowLayout->addLayout(sellingPriceLayout);
    leftLayout->addLayout(priceRowLayout, row++, 1);

    // 分类
    leftLayout->addWidget(new QLabel("分类:"), row, 0);
    m_categoryCombo = new QComboBox();
    // 从数据库动态加载分类到添加商品的分类下拉框
    for (const auto &category : categories) {
        int categoryId = category["category_id"].toInt();
        QString categoryName = category["category_name"].toString();
        m_categoryCombo->addItem(categoryName, categoryId);
    }
    leftLayout->addWidget(m_categoryCombo, row++, 1);

    // 折扣选项和添加按钮
    m_discountCheck = new QCheckBox("允许会员折扣");
    m_discountCheck->setChecked(true);
    leftLayout->addWidget(m_discountCheck, row, 0, 1, 2);

    m_addProductBtn = new QPushButton("添加商品");
    m_addProductBtn->setStyleSheet(
        "QPushButton { background-color: #28a745; color: white; border: none; padding: 10px; border-radius: 4px; font-weight: bold; }"
        "QPushButton:hover { background-color: #218838; }"
        "QPushButton:pressed { background-color: #1e7e34; }"
        "QPushButton:disabled { background-color: #b3dfb7; }"
    );
    leftLayout->addWidget(m_addProductBtn, ++row, 0, 1, 2);

    leftMainLayout->addWidget(formContent);

    // 右侧：统计信息
    QWidget *rightPanel = new QWidget(m_bottomPanel);
    rightPanel->setStyleSheet("background: white; border-radius: 6px;");
    QVBoxLayout *rightMainLayout = new QVBoxLayout(rightPanel);
    rightMainLayout->setContentsMargins(0, 0, 0, 0);

    // 统计标题
    QLabel *statsTitle = new QLabel("商品统计");
    statsTitle->setStyleSheet("background: #e9ecef; padding: 10px; border-top-left-radius: 6px; border-top-right-radius: 6px; font-weight: bold;");
    statsTitle->setAlignment(Qt::AlignCenter);
    rightMainLayout->addWidget(statsTitle);

    // 统计内容
    QWidget *statsContent = new QWidget();
    QVBoxLayout *rightLayout = new QVBoxLayout(statsContent);
    rightLayout->setContentsMargins(15, 15, 15, 15);
    rightLayout->setSpacing(15);

    // 总进货价 - 字体再放大两号
    QHBoxLayout *totalPurchaseLayout = new QHBoxLayout();
    QLabel *purchaseLabel = new QLabel("总进价:");
    purchaseLabel->setStyleSheet("font-size: 16px;"); // 再放大两号
    totalPurchaseLayout->addWidget(purchaseLabel);

    m_totalPurchaseLabel = new QLabel("¥ 0.00");
    // 字体再放大两号并加粗
    m_totalPurchaseLabel->setStyleSheet("font-weight: bold; color: #dc3545; font-size: 18px;");
    totalPurchaseLayout->addWidget(m_totalPurchaseLabel);
    totalPurchaseLayout->addStretch();
    rightLayout->addLayout(totalPurchaseLayout);

    // 总售价 - 字体再放大两号
    QHBoxLayout *totalSellingLayout = new QHBoxLayout();
    QLabel *sellingLabel = new QLabel("总售价:");
    sellingLabel->setStyleSheet("font-size: 16px;"); // 再放大两号
    totalSellingLayout->addWidget(sellingLabel);

    m_totalSellingLabel = new QLabel("¥ 0.00");
    // 字体再放大两号并加粗
    m_totalSellingLabel->setStyleSheet("font-weight: bold; color: #28a745; font-size: 18px;");
    totalSellingLayout->addWidget(m_totalSellingLabel);
    totalSellingLayout->addStretch();
    rightLayout->addLayout(totalSellingLayout);

    // 分类统计 - 字体再放大两号
    QLabel *categoryTitle = new QLabel("分类统计:");
    // 标题再放大两号
    categoryTitle->setStyleSheet("font-weight: bold; margin-top: 10px; font-size: 16px;");
    rightLayout->addWidget(categoryTitle);

    m_categoryStatsLabel = new QLabel("暂无数据");
    m_categoryStatsLabel->setWordWrap(true);
    // 内容再放大两号
    m_categoryStatsLabel->setStyleSheet("color: #6c757d; font-size: 17px; line-height: 1.6; background: #f8f9fa; padding: 10px; border-radius: 4px;");
    rightLayout->addWidget(m_categoryStatsLabel);

    rightLayout->addStretch();
    rightMainLayout->addWidget(statsContent);

    // 将左右面板添加到底部布局
    bottomLayout->addWidget(leftPanel, 2);
    bottomLayout->addWidget(rightPanel, 1);

    // 主布局组装：顶部面板 -> 表格 -> 底部面板
    m_mainLayout->addWidget(m_topPanel);
    m_mainLayout->addWidget(m_tableView, 1);
    m_mainLayout->addWidget(m_bottomPanel);

    // 更新全局样式表（核心修改：移除box-shadow，用加深边框替代聚焦效果）
    this->setStyleSheet(
        "ProductBrowsePanel { background-color: #f8f9fa; }"
        "QTableView { "
        "   background-color: white; "
        "   gridline-color: #dee2e6; "
        "   color: #212529; "
        "   border: 1px solid #dee2e6; "
        "   border-radius: 4px; "
        "}"
        "QTableView::item { "
        "   padding: 5px; "
        "   border-bottom: 1px solid #dee2e6; "
        "}"
        "QTableView::item:selected { "
        "   background-color: #007bff; "
        "   color: white; "
        "}"
        "QHeaderView::section { "
        "   background-color: #f8f9fa; "
        "   color: #495057; "
        "   padding: 8px; "
        "   border: none; "
        "   border-bottom: 2px solid #dee2e6; "
        "}"
        "QLabel { color: #495057; }"
        "QLineEdit { "
        "   border: 1px solid #ced4da; "
        "   padding: 6px 10px; "
        "   border-radius: 4px; "
        "   background: white; "
        "   color: #495057; "
        "   selection-background-color: #b3d7ff; "
        "}"
        "QLineEdit:focus { "
        "   border: 1px solid #4da6ff; /* 加深边框替代box-shadow，保留聚焦反馈 */"
        "   outline: 0; "
        "}"
        "QDoubleSpinBox { "
        "   border: 1px solid #ced4da; "
        "   padding: 6px 10px; "
        "   border-radius: 4px; "
        "   background: white; "
        "   color: #495057; "
        "}"
        "QDoubleSpinBox:focus { "
        "   border: 1px solid #4da6ff; /* 同QLineEdit，保持样式统一 */"
        "   outline: 0; "
        "}"
        "QComboBox { "
        "   border: 1px solid #ced4da; "
        "   padding: 6px 10px; "
        "   border-radius: 4px; "
        "   background: white; "
        "   color: #495057; "
        "}"
        "QComboBox:focus { "
        "   border: 1px solid #4da6ff; /* 同上述控件，统一聚焦样式 */"
        "   outline: 0; "
        "}"
        "QComboBox QAbstractItemView { "
        "   border: 1px solid #ced4da; "
        "   background: white; "
        "   selection-background-color: #007bff; "
        "   selection-color: white; "
        "}"
        "QCheckBox { color: #495057; }"
        "QCheckBox::indicator { "
        "   width: 18px; "
        "   height: 18px; "
        "}"
        "QCheckBox::indicator:checked { "
        "   background-color: #007bff; "
        "   border: 1px solid #007bff; "
        "}"
        // 底部面板渐变背景 - 柔和的绿色渐变（Qt 5.12支持qlineargradient）
        "#bottomPanel {"
        "   background: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #d4fc79, stop:1 #96e6a1);"
        "   border-top: 1px solid #dee2e6;"
        "}"
    );
}

// 绑定控件信号与槽函数
void ProductBrowsePanel::setupConnections()
{
    // 刷新按钮点击
    connect(m_refreshButton, &QPushButton::clicked, this, &ProductBrowsePanel::onRefreshButtonClicked);

    // 搜索框：文本变化触发搜索
    connect(m_searchEdit, &QLineEdit::textChanged, this, &ProductBrowsePanel::onSearchTextChanged);

    // 分类筛选：下拉框选择变化触发筛选
    connect(m_categoryFilter, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &ProductBrowsePanel::onCategoryFilterChanged);

    // 添加商品按钮点击
    connect(m_addProductBtn, &QPushButton::clicked, this, &ProductBrowsePanel::onAddButtonClicked);
}

// 刷新表格数据：调用模型层加载所有商品
void ProductBrowsePanel::refreshData()
{
    m_model->loadAllProducts();
    updateStatistics();
}

void ProductBrowsePanel::onAddButtonClicked()
{
    // 收集表单数据
    QMap<QString, QVariant> productData;
    productData["product_name"] = m_productNameEdit->text();
    productData["specification"] = m_specificationEdit->text();
    productData["color"] = m_colorEdit->text();
    productData["supplier"] = m_supplierEdit->text();
    productData["purchase_price"] = m_purchasePriceSpin->value();
    productData["selling_price"] = m_sellingPriceSpin->value();
    productData["category_id"] = m_categoryCombo->currentData();
    productData["allow_member_discount"] = m_discountCheck->isChecked();

    // 验证必填字段
    if (productData["product_name"].toString().isEmpty()) {
        QMessageBox::warning(this, "输入错误", "商品名称不能为空");
        return;
    }

    // 调用模型添加商品
    if (m_model->addProduct(productData)) {
        // 添加成功，清空表单
        m_productNameEdit->clear();
        m_specificationEdit->clear();
        m_colorEdit->clear();
        m_supplierEdit->clear();
        m_purchasePriceSpin->setValue(0.01);
        m_sellingPriceSpin->setValue(0.01);
        m_discountCheck->setChecked(true);

        // 更新统计信息
        updateStatistics();

        QMessageBox::information(this, "成功", "商品添加成功");
    } else {
        QMessageBox::warning(this, "错误", "添加商品失败");
    }
}

// 刷新按钮点击：触发数据刷新
void ProductBrowsePanel::onRefreshButtonClicked()
{
    refreshData();
}

// 搜索框文本变化：调用模型层按名称搜索商品
void ProductBrowsePanel::onSearchTextChanged(const QString &text)
{
    m_model->searchProducts(text);
}

//筛选
void ProductBrowsePanel::onCategoryFilterChanged(int index)
{
    Q_UNUSED(index);
    int categoryId = m_categoryFilter->currentData().toInt();

    // 调用模型的分类筛选方法
    m_model->filterByCategory(categoryId);
}

void ProductBrowsePanel::updateStatistics()
{
    // 获取所有商品数据
    QVector<QMap<QString, QVariant>> products = m_model->getAllProducts();

    // 计算总进货价和总售价
    double totalPurchase = 0.0;
    double totalSelling = 0.0;

    for (const auto &product : products) {
        totalPurchase += product["purchase_price"].toDouble();
        totalSelling += product["selling_price"].toDouble();
    }

    // 更新UI
    m_totalPurchaseLabel->setText(QString("¥ %1").arg(totalPurchase, 0, 'f', 2));
    m_totalSellingLabel->setText(QString("¥ %1").arg(totalSelling, 0, 'f', 2));

    // 获取分类统计信息
    QMap<int, int> categoryStats = m_model->getCategoryStatistics();

    // 获取分类名称映射
    QVector<QMap<QString, QVariant>> categories = m_model->getAllCategories();
    QMap<int, QString> categoryNameMap;
    for (const auto &category : categories) {
        int categoryId = category["category_id"].toInt();
        QString categoryName = category["category_name"].toString();
        categoryNameMap[categoryId] = categoryName;
    }

    // 更新分类统计
    QString categoryStatsText;
    for (auto it = categoryStats.begin(); it != categoryStats.end(); ++it) {
        QString categoryName = categoryNameMap.value(it.key(), "未知分类");

        if (!categoryStatsText.isEmpty()) {
            categoryStatsText += "\n";
        }
        categoryStatsText += QString("%1: %2种商品").arg(categoryName).arg(it.value());
    }

    m_categoryStatsLabel->setText(categoryStatsText.isEmpty() ? "暂无数据" : categoryStatsText);
}
